<?php

class offersFormComponents extends sfComponents
{
    public function executeRender()
    {
        $this->form = new sfForm();

		// Form widgets
		$this->form->setWidgets(array(
			'name'		=> new sfWidgetFormInputText(array('label' => 'Kontaktisik:')),
			'company'	=> new sfWidgetFormInputText(array('label' => 'Ettevote:')),
			'phone'		=> new sfWidgetFormInputText(array('label' => 'Telefon:')),
			'email'		=> new sfWidgetFormInputText(array('label' => 'E-mail:')),
			'message'	=> new sfWidgetFormTextarea(array('label'  => 'Teade:')),
			'captcha'	=> new sfWidgetFormInputText(),
		));

		// Form validators
		$this->form->setValidators(array(
			'name'		=> new sfValidatorString(array('max_length' => 64)),
			'company'	=> new sfValidatorString(array('max_length' => 128)),
			'phone'		=> new sfValidatorString(array('max_length' => 32)),
			'email'		=> new sfValidatorEmail(array()),
			'message'	=> new sfValidatorString(array('max_length' => 2048)),
			'captcha'	=> new sfCaptchaGDValidator(array('length' => 4))
		));

		$this->form->getWidgetSchema()->setNameFormat('feedback[%s]');


		if($this->getRequest()->isMethod('post')) {
			$this->form->bind($this->getRequest()->getParameter('feedback'));

            // Array of errors
            $this->errors = array();
            
			if($this->form->isValid()) {
                $path = $_SERVER['DOCUMENT_ROOT'] . '/internal/' . session_id();

				// Find attached files
                if(is_dir($path)) {
                    $files = array();
                    $size  = 0;

                    foreach(glob($path . '/*') as $file) {
                        $files[] = str_replace('.noexecute', '', $file);
                        $size    = filesize($file);
                    }

                    if($files <= 5 && $size <= 1024000000) {
                        
                    } else $this->errors[] = 'Failide suurus rohkem kui 10 MB voi neid on rohkem kui 5';
                } else $files = array();
                
                sfContext::getInstance()->getConfiguration()->loadHelpers('Variable');

                    /**
                     *  Replacement patterns
                     */
                    $parameters = $this->getRequest()->getParameter('feedback');
                    $patterns   = array(
                        '%name%'    => $parameters['name'],
                        '%company%' => $parameters['company'],
                        '%phone%'   => $parameters['phone'],
                        '%email%'   => $parameters['email'],
                        '%message%' => $parameters['message']
                    );

                    // Send the message
                    $message = sfContext::getInstance()->getMailer()->compose(
                        variable('admin_email'),
                        variable('admin_email'),
                        'Uus pakkumine',
                        str_replace(
                            array_keys($patterns),
                            $patterns,
                            variable('message_body')
                        )
                    );

                    // Attach the files to the message
                    foreach($files as $attachement) {
                        $message = $message->attach(
                            Swift_Attachment::fromPath($file)
                        );
                    }

                    sfContext::getInstance()->getMailer()->send($message);

                    // Remove all user files
                    foreach($files as $file) {
                        unlink($file . '.noexecute');
                    }

                    rmdir($_SERVER['DOCUMENT_ROOT'] . '/internal/' . session_id());

                    // Set the flash message
                    $this->getUser()->setFlash('success', 'Teie pakkumine saadetud');

                    $actionInstance = sfContext::getInstance()->getActionStack()->getLastEntry()->getActionInstance();
                    
                    $actionInstance->redirect(
                        $actionInstance->getRequest()->getReferer() ? $actionInstance->getRequest()->getReferer() : '/'
                    );

			} else $this->errors[] = 'Sisestatud andmed ei ole oige';
		}	
    }
};

?>
